package com.zbs.framework.common.mybatis;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;

import java.util.List;
public class CommonServiceImpl<M extends CommonMapper<T>, T> extends ServiceImpl<M, T> implements CommonService<T> {
    private static final Integer BATCH_SIZE = 100;

    @Override
    public Boolean saveIgnoreBatch(List<T> list, int batchSize) {
        if (CollectionUtils.isEmpty(list)) {
            return true;
        }

        batchSize = batchSize < 1 ? BATCH_SIZE : batchSize;

        if (list.size() <= batchSize) {
            return SqlHelper.retBool(baseMapper.insertIgnoreBatchAllColumn(list));
        }

        for (int fromIdx = 0, endIdx = batchSize; ; fromIdx += batchSize, endIdx += batchSize) {
            if (endIdx > list.size()) {
                endIdx = list.size();
            }
            baseMapper.insertIgnoreBatchAllColumn(list.subList(fromIdx, endIdx));
            if (endIdx == list.size()) {
                return true;
            }
        }
    }
    @Override
    public Boolean saveIgnoreBatch(List<T> list) {
        return saveIgnoreBatch(list, BATCH_SIZE);
    }

    @Override
    public Boolean saveIgnore(T entity) {
        return SqlHelper.retBool(this.baseMapper.insertIgnoreColumn(entity));
    }
}

